﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml.Serialization;
using System.Xml;
using System.IO;
using System.Xml.Linq;

namespace WsusWebAdmin.Web.Wsus
{
    public class FileDataProvider:IWsusDataProvider
    {
        private IEnumerable<WsusHostData> data;

        public FileDataProvider(string fileName)
        {
            FileName = fileName;
        }

        public IEnumerable<WsusHostData> GetHosts()
        {
            LoadDataIfNeeded();
            return data;
        }

        private void LoadDataIfNeeded()
        {
            if (data == null)
            {
                var doc = XDocument.Load(FileName);

                data = doc.Root.Elements("server").Select(x => new WsusHostData
                {
                    Name = x.Element("name").Value,
                    RemotingUrl = x.Element("remotingUrl").Value
                });
            }
        }

        public WsusHostData GetHost(string name)
        {
            LoadDataIfNeeded();
            return data.Where(x => x.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase)).SingleOrDefault();
        }

        protected string FileName { get; set; }
    }
}